import cookieShare from "@/plugins/cookieShare"
import Cookies from "js-cookie"

const TokenKey = 'BUGCOME-Token'
const ClientKey = 'client'

export function getToken() {
  //return localStorage.getItem(TokenKey)
  return cookieShare.get(TokenKey)
}

export function setToken(token) {
  //return localStorage.setItem(TokenKey, token)
  return cookieShare.set(TokenKey, token, null, import.meta.env.VITE_Domain)
}


export function removeToken() {
  return Cookies.remove(TokenKey)
}

export function parseJwt() {
  try {
   
    let token =cookieShare.get(TokenKey)
    if(token == null)
    {
      return ;
    }
    console.log('1122122',token)
    // JWT由三部分组成：header.payload.signature，取中间的payload部分
    const base64Url = token.split('.')[1];
    if (!base64Url) throw new Error('无效的Token格式');

    // Base64解码（处理URL安全字符）
    const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
    const jsonPayload = decodeURIComponent(
      atob(base64)
        .split('')
        .map(c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))
        .join('')
    );

    // 转换为JSON对象并处理日期格式（如exp过期时间）
    const payload = JSON.parse(jsonPayload);
    const userdataStr =JSON.parse(payload['http://schemas.microsoft.com/ws/2008/06/identity/claims/userdata']);
    payload.user = userdataStr;
    if (payload.exp) {
      // 将时间戳转换为Date对象
      payload.exp = new Date(payload.exp * 1000);
    }
    if (payload.iat) {
      payload.iat = new Date(payload.iat * 1000);
    }

    return payload;
  } catch (e) {
    console.error('解析Token失败：', e.message);
    return null;
  }
}
